﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UseOpenXML.Models;

namespace UseOpenXML.Controllers
{
    public class HomeController : Controller
    {

        private readonly IWebHostEnvironment _webHostEnvironment;
        public HomeController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region OpenXML
        /// <summary>
        /// 导出模板
        /// </summary>
        /// <returns></returns>
        public IActionResult ExportOpenXML(int type)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                using (WordprocessingDocument doc = WordprocessingDocument.Create(ms, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
                {
                    switch (type)
                    {
                        case 1:
                            SimpleText(doc);//简单文本
                            break;
                        case 2:
                            SimpleTable(doc);//简单表格
                            break;
                        case 3:
                            InsertImage(doc);//插入图片
                            break;
                        case 4:
                            InsertBookmark(doc);//插入书签
                            SearchBookmark(doc);//查找书签，并替换
                            break;
                        default:
                            break;
                    }
                }

                return File(ms.ToArray(), "application/octet-stream", "自定义Word.docx");
            }
            catch (Exception ex)
            {
                Response.ContentType = "text/plain;charset=utf-8";
                Response.WriteAsync("导出失败，请联系管理员，错误描述：" + ex.Message);
                return null;
            }
        }

        #region word文档设置

        void SimpleText(WordprocessingDocument doc)
        {
            //word解压缩后的文档
            /*
<?xml version="1.0" encoding="utf-8"?>
<w:document
    xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        <w:p>
            <w:r>
                <w:rPr>
                    <w:b />
                </w:rPr>
                <w:t>Hello, Word!</w:t>
            </w:r>
        </w:p>
    </w:body>
</w:document>
             */

            // w:document
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            // w:body
            Body body = mainPart.Document.AppendChild(new Body());

            // w:p 段落
            Paragraph para = body.AppendChild(new Paragraph());
            // w:r 文本区域界限
            Run run = para.AppendChild(new Run());

            // w:rPr 段落属性 w:b粗体格式
            RunProperties runProperties = run.AppendChild(new RunProperties(new Bold()));

            // w:t 文本
            run.AppendChild(new Text("Hello, Word!"));
        }

        void SimpleTable(WordprocessingDocument doc)
        {
            //word解压缩后的文档
            /*
<?xml version="1.0" encoding="utf-8"?>
<w:document
    xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        <w:tbl>
            <w:tblPr>
                <w:tblStyle w:val="TableGrid" />
                <w:tblW w:w="5000" w:type="pct" />
            </w:tblPr>
            <w:tblGrid>
                <w:gridCol />
                <w:gridCol />
                <w:gridCol />
            </w:tblGrid>
            <w:tr>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>1</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>2</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
                <w:tc>
                    <w:p>
                        <w:r>
                            <w:t>3</w:t>
                        </w:r>
                    </w:p>
                </w:tc>
            </w:tr>
        </w:tbl>
    </w:body>
</w:document>
             */

            // w:document
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            // w:body
            Body body = mainPart.Document.AppendChild(new Body());

            // w:tbl 创建一个表
            Table tbl = new Table();

            // w:tblPr 表属性
            TableProperties tableProp = new TableProperties();

            // w:tblStyle 表格样式
            TableStyle tableStyle = new TableStyle() { Val = "TableGrid" };
            // w:tblW 表宽度
            TableWidth tableWidth = new TableWidth() { Width = "5000", Type = TableWidthUnitValues.Pct };

            tableProp.Append(tableStyle, tableWidth);
            tbl.AppendChild(tableProp);

            // w:tblGrid 表列设置
            TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn());
            tbl.AppendChild(tg);

            // w:tr 行
            TableRow tr1 = new TableRow();

            // w:tc 单元格 w:p 段落 w:r 文本区域界限  w:t 文本
            TableCell tc1 = new TableCell(new Paragraph(new Run(new Text("1"))));
            TableCell tc2 = new TableCell(new Paragraph(new Run(new Text("2"))));
            TableCell tc3 = new TableCell(new Paragraph(new Run(new Text("3"))));
            tr1.Append(tc1, tc2, tc3);

            tbl.AppendChild(tr1);
            body.AppendChild(tbl);
        }

        void InsertImage(WordprocessingDocument doc)
        {
            //word解压缩后的文档
            /*
<?xml version="1.0" encoding="utf-8"?>
<w:document
    xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        ……
    </w:body>
</w:document>
             */

            // w:document
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();

            // w:body
            Body body = mainPart.Document.AppendChild(new Body());

            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
            var imgName = "avatar.png";
            var fileName = Path.Combine(_webHostEnvironment.WebRootPath, "images", imgName);
            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }
            AddImageToBody(doc, mainPart.GetIdOfPart(imagePart), imgName);
        }
        /// <summary>
        /// 若要将图像添加到正文，请首先定义对图像的引用。 然后将引用追加到正文。 该元素应该位于 Run 中
        /// </summary>
        /// <param name="wordDoc"></param>
        /// <param name="relationshipId"></param>
        /// <param name="fileName"></param>
        void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, string fileName)
        {
            // 定义图片引用
            /*
<w:p>
    <w:r>
        <w:drawing>
            <wp:inline distT="0" distB="0" distL="0" distR="0" wp14:editId="50D07946"
                xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing"
                xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
                <wp:extent cx="990000" cy="792000" />
                <wp:effectExtent l="0" t="0" r="0" b="0" />
                <wp:docPr id="1" name="Picture 1" />
                <wp:cNvGraphicFramePr>
                    <a:graphicFrameLocks noChangeAspect="1"
                        xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" />
                </wp:cNvGraphicFramePr>
                <a:graphic
                    xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
                    <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
                        <pic:pic
                            xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
                            <pic:nvPicPr>
                                <pic:cNvPr id="0" name="avatar.png" />
                                <pic:cNvPicPr />
                            </pic:nvPicPr>
                            <pic:blipFill>
                                <a:blip r:embed="R97b55bdbfb6140b9" cstate="print"
                                    xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
                                    <a:extLst>
                                        <a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}" />
                                    </a:extLst>
                                </a:blip>
                                <a:stretch>
                                    <a:fillRect />
                                </a:stretch>
                            </pic:blipFill>
                            <pic:spPr>
                                <a:xfrm>
                                    <a:off x="0" y="0" />
                                    <a:ext cx="990000" cy="792000" />
                                </a:xfrm>
                                <a:prstGeom prst="rect">
                                    <a:avLst />
                                </a:prstGeom>
                            </pic:spPr>
                        </pic:pic>
                    </a:graphicData>
                </a:graphic>
            </wp:inline>
        </w:drawing>
    </w:r>
</w:p>
             */
            var element =
                 new Drawing(
                     new DW.Inline(
                         new DW.Extent() { Cx = 990000L, Cy = 792000L },
                         new DW.EffectExtent()
                         {
                             LeftEdge = 0L,
                             TopEdge = 0L,
                             RightEdge = 0L,
                             BottomEdge = 0L
                         },
                         new DW.DocProperties()
                         {
                             Id = (UInt32Value)1U,
                             Name = "Picture 1"
                         },
                         new DW.NonVisualGraphicFrameDrawingProperties(
                             new A.GraphicFrameLocks() { NoChangeAspect = true }),
                         new A.Graphic(
                             new A.GraphicData(
                                 new PIC.Picture(
                                     new PIC.NonVisualPictureProperties(
                                         new PIC.NonVisualDrawingProperties()
                                         {
                                             Id = (UInt32Value)0U,
                                             Name = fileName
                                         },
                                         new PIC.NonVisualPictureDrawingProperties()),
                                     new PIC.BlipFill(
                                         new A.Blip(
                                             new A.BlipExtensionList(
                                                 new A.BlipExtension()
                                                 {
                                                     Uri =
                                                        "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                 })
                                         )
                                         {
                                             Embed = relationshipId,
                                             CompressionState =
                                             A.BlipCompressionValues.Print
                                         },
                                         new A.Stretch(
                                             new A.FillRectangle())),
                                     new PIC.ShapeProperties(
                                         new A.Transform2D(
                                             new A.Offset() { X = 0L, Y = 0L },
                                             new A.Extents() { Cx = 990000L, Cy = 792000L }),
                                         new A.PresetGeometry(
                                             new A.AdjustValueList()
                                         )
                                         { Preset = A.ShapeTypeValues.Rectangle }))
                             )
                             { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                     )
                     {
                         DistanceFromTop = (UInt32Value)0U,
                         DistanceFromBottom = (UInt32Value)0U,
                         DistanceFromLeft = (UInt32Value)0U,
                         DistanceFromRight = (UInt32Value)0U,
                         EditId = "50D07946"
                     });

            // Append the reference to body, the element should be in a Run.
            wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
        }

        void InsertBookmark(WordprocessingDocument doc)
        {
            //word解压缩后的文档
            /*
<?xml version="1.0" encoding="utf-8"?>
<w:document
    xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        <w:p>
            <w:r>
                <w:rPr>
                    <w:b />
                </w:rPr>
                <w:t>姓名：</w:t>
            </w:r>
            <w:bookmarkStart w:name="名字" w:id="1" />
            <w:r>
                <w:t>小明</w:t>
            </w:r>
            <w:bookmarkEnd w:id="1" />
        </w:p>
    </w:body>
</w:document>
             */

            // w:document
            MainDocumentPart mainPart = doc.AddMainDocumentPart();
            mainPart.Document = new Document();
            // w:body
            Body body = mainPart.Document.AppendChild(new Body());

            // w:p 段落
            Paragraph para = body.AppendChild(new Paragraph());

            // w:r 文本区域界限
            Run run = para.AppendChild(new Run());

            // w:rPr 段落属性 w:b粗体格式
            RunProperties runProperties = run.AppendChild(new RunProperties(new Bold()));

            // w:t 文本
            run.AppendChild(new Text("姓名："));

            // w:bookmarkStart 开始书签
            para.AppendChild(new BookmarkStart()
            {
                Id = new StringValue("1"),
                Name = new StringValue("名字")
            });

            // w:r 文本区域界限
            Run run2 = para.AppendChild(new Run());

            // w:t 文本
            run2.AppendChild(new Text("小明"));

            // w:bookmarkEnd 结束书签
            para.AppendChild(new BookmarkEnd()
            {
                Id = new StringValue("1"),//对应开始书签的id
            });
        }

        void SearchBookmark(WordprocessingDocument doc)
        {
            //参考链接 https://stackoverflow.com/questions/3308299/replace-bookmark-text-in-word-file-using-open-xml-sdk
            //获取文档所有标签
            var bookmarkStarts = doc.MainDocumentPart.Document.Descendants<BookmarkStart>().ToList();

            //查找 名字 标签
            var bookmarkStart = bookmarkStarts.FirstOrDefault(bm => bm.Name == "名字");

            //替换
            Run bookmarkText = bookmarkStart.NextSibling<Run>();
            if (bookmarkText != null)
            {
                bookmarkText.GetFirstChild<Text>().Text = "王小明";
            }

        }
        #endregion

        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public IActionResult UploadOpenXML(IFormFile file)
        {
            JsonResultModel result = new JsonResultModel();
            try
            {
                #region 验证文件格式

                if (Request.Form.Files.Count == 0)
                {
                    result.IsOk = false;
                    result.Msg = "请选择上传文件";
                    return Json(result);
                }
                string fileExt = System.IO.Path.GetExtension(file.FileName).ToLower();
                if (fileExt != ".docx")
                {
                    result.IsOk = false;
                    result.Msg = "上传的文件类型必须为.docx类型";
                    return Json(result);
                }

                #endregion 验证文件格式

                #region 获取文件数据


                #endregion 获取文件数据

                result.Data = null;
                return Json(result);
            }
            catch (Exception ex)
            {
                result.IsOk = false;
                result.Msg = "导入出错:" + ex.Message;
            }

            return Json(result);
        }
        #endregion

    }
}
